package com.yhuso.test.serializableAndExternalizable;

import java.io.*;

/**
 * Created by ehsy_it on 2016/4/1.
 */
public class User2 implements Externalizable {
    private String name;
    private int age;
    private int people;
    private int money;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }

    public int getPeople() {
        return people;
    }

    public void setPeople(int people) {
        this.people = people;
    }

    @Override
    public String toString() {
        return "User2{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", people=" + people +
                ", money=" + money +
                '}';
    }

    /**
     * 对Externalizable的理解，它继承自Serializable接口
     * 我们可根据需要自己实现序列化/反序列化的过程
     * @param out
     * @throws IOException
     */
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeInt(money);//这一步是给age写值300
        out.writeInt(age);//这一步是给people写值1
        out.writeInt(people);//这一步是给money写值20
        out.writeObject(name);//这一步不能移到下边，否则类型不匹配，报异常，严格遵循类中声明的顺序

        /*对于同样类型的属性,是按类中定义的顺序读写的
          如本类中定义顺序为age,people,money
          那么写入时，则第一个位置写
          总结：写和读的顺序一致就行了
         */
    }

    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        this.money = in.readInt();//读出的是300
        this.age = in.readInt();//读出的是1
        this.people = in.readInt();//读出的是20
        this.name = in.readObject().toString();
    }


}
